<template>
  <div class="signature-container">
    <canvas
      ref="canvas"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseup="stopDrawing"
      @mouseout="stopDrawing"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="stopDrawing"
      style="touch-action: none"
    ></canvas>

    <div class="controls">
      <div class="action-buttons">
        <button class="btn" @click="clearCanvas">清除</button>
        <!-- <button class="btn" :disabled="!canUndo" @click="undo">撤销</button> -->
        <!-- <button v-if="showSaveButton" class="btn primary" @click="saveSignature">完成签名</button> -->
      </div>
    </div>

    <!-- <div class="signature-preview" v-if="savedSignatureUrl">
      <h3>签名预览</h3>
      <img :src="savedSignatureUrl" alt="保存的签名预览" />
    </div> -->
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, defineEmits, defineExpose, defineProps } from "vue";

// 定义props
const props = defineProps({
  showSaveButton: {
    type: Boolean,
    default: true,
  },
});

// 定义事件
const emit = defineEmits(["signature-change"]);

// 响应式数据
const canvas = ref(null);
const penColor = ref("#000000");
const penSize = ref(3);
const savedSignatureUrl = ref("");

// 绘图状态
const drawingState = reactive({
  isDrawing: false,
  lastX: 0,
  lastY: 0,
  ctx: null,
  drawingHistory: [],
  currentStep: -1,
});

// 计算属性
const canUndo = ref(false);

// 初始化画布
const initCanvas = () => {
  if (!canvas.value) return;

  drawingState.ctx = canvas.value.getContext("2d");
  resizeCanvas();

  drawingState.ctx.fillStyle = "white";
  drawingState.ctx.fillRect(0, 0, canvas.value.width, canvas.value.height);
  updatePenSettings();
};

// 调整画布大小
const resizeCanvas = () => {
  if (!canvas.value) return;

  const container = canvas.value.parentElement;
  canvas.value.width = container.clientWidth;
  canvas.value.height = 300;
  redraw();
};

// 更新笔触设置
const updatePenSettings = () => {
  if (!drawingState.ctx) return;

  drawingState.ctx.strokeStyle = penColor.value;
  drawingState.ctx.lineWidth = penSize.value;
  drawingState.ctx.lineCap = "round";
  drawingState.ctx.lineJoin = "round";
};

// 获取坐标位置
const getPosition = (e) => {
  let x, y;
  if (e.type.includes("touch")) {
    const rect = canvas.value.getBoundingClientRect();
    x = e.touches[0].clientX - rect.left;
    y = e.touches[0].clientY - rect.top;
  } else {
    x = e.offsetX;
    y = e.offsetY;
  }
  return [x, y];
};

// 保存绘图状态
const saveDrawingState = () => {
  if (!drawingState.ctx) return;

  // 如果撤销后又有新绘制，删除后面的历史记录
  if (drawingState.currentStep < drawingState.drawingHistory.length - 1) {
    drawingState.drawingHistory = drawingState.drawingHistory.slice(
      0,
      drawingState.currentStep + 1
    );
  }

  const imageData = drawingState.ctx.getImageData(0, 0, canvas.value.width, canvas.value.height);
  drawingState.drawingHistory.push(imageData);
  drawingState.currentStep++;
  canUndo.value = drawingState.currentStep > 0;
};

// 重绘
const redraw = () => {
  if (!drawingState.ctx) return;

  if (drawingState.currentStep >= 0) {
    drawingState.ctx.putImageData(drawingState.drawingHistory[drawingState.currentStep], 0, 0);
  } else {
    drawingState.ctx.fillStyle = "white";
    drawingState.ctx.fillRect(0, 0, canvas.value.width, canvas.value.height);
    updatePenSettings();
  }
};

// 开始绘制
const startDrawing = (e) => {
  drawingState.isDrawing = true;
  [drawingState.lastX, drawingState.lastY] = getPosition(e);

  // 保存当前绘图状态
  saveDrawingState();
};

// 绘制过程
const draw = (e) => {
  if (!drawingState.isDrawing || !drawingState.ctx) return;

  updatePenSettings();

  const [currentX, currentY] = getPosition(e);

  drawingState.ctx.beginPath();
  drawingState.ctx.moveTo(drawingState.lastX, drawingState.lastY);
  drawingState.ctx.lineTo(currentX, currentY);
  drawingState.ctx.stroke();
  [drawingState.lastX, drawingState.lastY] = [currentX, currentY];
};

// 结束绘制
const stopDrawing = () => {
  drawingState.isDrawing = false;
};

// 触摸事件处理
const handleTouchStart = (e) => {
  //e.preventDefault();
  startDrawing(e);
};

const handleTouchMove = (e) => {
  //e.preventDefault();
  draw(e);
};

// 撤销操作
const undo = () => {
  if (drawingState.currentStep > 0) {
    drawingState.currentStep--;
    redraw();
    canUndo.value = drawingState.currentStep > 0;
  } else {
    clearCanvas();
  }
};

// 清除画布
const clearCanvas = () => {
  if (!drawingState.ctx) return;

  drawingState.ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
  drawingState.ctx.fillStyle = "white";
  drawingState.ctx.fillRect(0, 0, canvas.value.width, canvas.value.height);
  updatePenSettings();

  drawingState.drawingHistory = [];
  drawingState.currentStep = -1;
  canUndo.value = false;
  savedSignatureUrl.value = "";
  // 向父组件发送清空事件
  emit("signature-change", null);
};

// 获取签名数据
const getSignatureData = () => {
  if (drawingState.currentStep < 0) {
    return null;
  }
  return canvas.value.toDataURL("image/png");
};

// 保存签名
const saveSignature = () => {
  const dataURL = getSignatureData();
  if (!dataURL) {
    ElMessage.warning("请先签名！");
    return;
  }

  savedSignatureUrl.value = dataURL;
  // 向父组件发送签名数据
  emit("signature-change", dataURL);
  // ElMessage.success("签名成功");
};

// 窗口大小改变处理
const handleResize = () => {
  resizeCanvas();
};

// 组件挂载后初始化
onMounted(() => {
  nextTick(() => {
    initCanvas();
    window.addEventListener("resize", handleResize);
  });
});

// 暴露方法给父组件
defineExpose({
  getSignatureData,
  clearCanvas,
  saveSignature,
});
</script>

<style scoped>
.signature-container {
  background-color: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

canvas {
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: crosshair;
  display: block;
  width: 100%;
  height: 300px;
  background-color: white;
  touch-action: none;
}

.controls {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.pen-settings {
  display: flex;
  align-items: center;
  gap: 15px;
  flex-wrap: wrap;
}

.pen-settings label {
  font-weight: 500;
  color: var(--dark-color);
}

.pen-settings input[type="color"] {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.pen-settings input[type="range"] {
  width: 120px;
  height: 6px;
  border-radius: 3px;
  background: #ddd;
  outline: none;
  cursor: pointer;
}

.pen-settings span {
  font-weight: bold;
  color: var(--primary-color);
  min-width: 40px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.btn {
  padding: 12px 24px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  background-color: #f8f9fa;
  color: var(--dark-color);
  border: 1px solid #dee2e6;
}

.btn:hover {
  background-color: #e9ecef;
  transform: translateY(-1px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.btn.primary {
  background-color: var(--vue-color);
  color: white;
  border-color: var(--vue-color);
  background-color: #369870;
  border-color: #369870;
}

.btn.primary:hover {
  background-color: #369870;
  border-color: #369870;
}

.signature-preview {
  margin-top: 30px;
  text-align: center;
}

.signature-preview h3 {
  color: var(--dark-color);
  margin-bottom: 15px;
}

.signature-preview img {
  max-width: 100%;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .signature-container {
    padding: 15px;
  }

  .pen-settings {
    justify-content: center;
  }

  .action-buttons {
    justify-content: center;
  }

  .btn {
    flex: 1;
    min-width: 80px;
  }
}
</style>
